package org.dreamwork.jasmine2.template.impl;

import org.dreamwork.jasmine2.annotation.TemplateParser;
import org.dreamwork.jasmine2.template.ITemplate;
import org.dreamwork.jasmine2.template.ITemplateControl;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.xpath.*;

/**
 * Created by IntelliJ IDEA.
 * User: seth
 * Date: 2009-9-10
 * Time: 15:53:15
 */
@TemplateParser (XMLTemplateParser.class)
public class BaseTemplate implements ITemplate {
    protected Element root;
    protected String content;
    protected XPathFactory f = XPathFactory.newInstance ();

    public void setRootElement (Element root) {
        this.root = root;
    }

    public void setContent (String content) {
        this.content = content;
    }

    public String getContent () {
        return content;
    }

    public void instantiateIn (ITemplateControl control) {
        control.setTemplate (this);
    }

    public NodeList selectNodes (String xpath) {
        if (root == null) return null;
        try {
            XPath x = f.newXPath ();
            XPathExpression e = x.compile (xpath);
            return (NodeList) e.evaluate (root, XPathConstants.NODESET);
        } catch (XPathExpressionException ex) {
            throw new RuntimeException (ex);
        }
    }

    public Node selectSingleNode (String xpath) {
        if (root == null) return null;
        try {
            NodeList list = selectNodes (xpath);
            return list == null ? null : list.getLength () == 0 ? null : list.item (0);
        } catch (Exception ex) {
            throw new RuntimeException (ex);
        }
    }
}